import axios from 'axios';
import store from '../store/store';
import { authService } from '../services/auth';

const instance = axios.create({
  baseURL: '/deepseek',
  timeout: 5000
});

// 百度API专用实例 - 使用代理路径避免CORS问题
export const baiduInstance = axios.create({
  baseURL: '/baidu',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
});

export const tsnInstance = axios.create({
  baseURL: '/tsn',
  timeout: 20000,
  responseType: 'blob'
});

// 添加请求拦截器
instance.interceptors.request.use(async function (config) {
  const state = store.getState();
  const token = state.auth.accessToken;
  const expiresAt = state.auth.accessTokenExpiresAt || 0;
  const now = Date.now();
  // try silent refresh if expiring within 30s
  // 如果token存在且过期时间小于30秒，则尝试刷新token
  if (token && expiresAt - now < 30_000) {
    try { await authService.refreshToken(); } catch { /* ignore */ }
  }
  // 更新token到请求头
  const updated = store.getState().auth.accessToken;
  if (updated) {
    config.headers = config.headers || {};
    (config.headers as Record<string, string>)['Authorization'] = `Bearer ${updated}`;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response; // 正常响应直接返回
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 401: try refresh once, else redirect to login
  const original = error.config || {};
  //401错误处理
  if (error.response && error.response.status === 401 && !original.__retried) {
    original.__retried = true; // 防止重复重试401错误
    return authService.refreshToken()
      .then(() => instance(original))
      .catch(() => {
        // 刷新失败，清除登录状态并跳转登录页
        authService.logout();
        // use location to navigate to login (no router import here)
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
        return Promise.reject(error);
      });
  }
  return Promise.reject(error);
});

// 百度API响应拦截器
baiduInstance.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  console.error('百度API请求失败:', error);
  return Promise.reject(error);
});


export default instance; 
